package org.activequant.util.spring;

import java.io.File;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * Locates and provides all available application services.<br>
 * <br>
 * <b>History:</b><br>
 *  - [31.12.2007] Created (Erik Nijkamp)<br>
 *
 *  @author Erik Nijkamp
 *  
 */
public class ContextResolver {
	
    /**
     * <strong>1.</strong> If the given path(String) points to an existing File(XML file) it creates and returns a <strong>FileSystemXmlApplicationContext</strong> 
     * loading its definitions from the XML file found at the given path(String).<br/>
     * <strong>2.</strong> Otherwise if the given path(String) points to a valid resource(like XML file), it creates and returns a <strong>ClassPathXmlApplicationContext</strong>
     *  loading its definitions from the XML file found at the given path(String).<br/>
     * <strong>3.</strong> Otherwise it throws an IllegalArgumentException("Cannot locate spring context file '${path}'")
     * @param path
     * @return
     */
    public static ApplicationContext resolveContext(String path) {    	
    	return resolveContext(null, path);
    }
    /**
     * <strong>1.</strong> If the given path(String) points to an existing File(XML file) it creates and returns a <strong>FileSystemXmlApplicationContext</strong> 
     * (with the given parent(ApplicationContext), which can be null) loading its definitions from the XML file found at the given path(String).<br/>
     * <strong>2.</strong> Otherwise if the given path(String) points to a valid resource(like XML file), it creates and returns a <strong>ClassPathXmlApplicationContext </strong>
     * (with the given parent(ApplicationContext), which can be null) loading its definitions from the XML file found at the given path(String).<br/>
     * <strong>3.</strong> Otherwise it throws an IllegalArgumentException("Cannot locate spring context file '${path}'")
     * @param parent
     * @param path
     * @return
     */
    public static ApplicationContext resolveContext(ApplicationContext parent, String path) {    	
    	// filesystem
    	if(new File(path).exists()) {
    		return new FileSystemXmlApplicationContext(new String[] {path}, parent);
    	}
    	
    	// classpath
    	if(ServiceLocator.class.getClassLoader().getResource(path) != null) {
    		return new ClassPathXmlApplicationContext(new String[] {path}, parent);
    	}
    	
    	// error
    	throw new IllegalArgumentException("Cannot locate spring context file '"+path+"'");
    }

}
